package com.example.server.manage.gptdialogue.controller;


import cn.hutool.core.io.IORuntimeException;
import cn.hutool.http.HttpException;
import com.example.server.config.error.ErrorException;
import com.example.server.manage.gptdialogue.model.dto.ChatGptDTO;
import com.example.server.manage.gptdialogue.server.ChatGptService;
import com.example.server.manage.gptdialogue.server.ChatGptSseService;
import com.example.server.result.Result;
import com.plexpt.chatgpt.entity.chat.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletResponse;

/**
 * chatGpt 对话请求
 *
 * <p>
 * ::本代码由[兮家小二]提供的代码生成器生成,如有问题,请手动修改 ::作者CSDN:https://blog.csdn.net/qq_41463655
 * </p>
 *
 * @author ws
 * @email 1720696548@qq.com
 * @date 2022-04-25 18:08:22
 */
@RestController
@RequestMapping("/gpt")
public class ChatGptController {

    @Autowired
    private ChatGptService chatGptService;

    @Autowired
    private ChatGptSseService chatGptSseService;

    /**
     * 接口式 对话
     * @param dto
     * @return
     */
    @PostMapping(value = "/chat")
    @CrossOrigin
    public Result<Message> chat(@RequestBody ChatGptDTO dto) {
        try {
            return Result.success(chatGptService.chat(dto.getContent(), dto.getModel(), dto.getMaxTokens(), dto.getTemperature()));
        } catch (HttpException e) {
            throw new ErrorException("请求 openai 遇到点网络问题 HttpException");
        } catch (IORuntimeException e) {
            throw new ErrorException("请求 openai 遇到点网络问题 IORuntimeException");
        }
    }

    /**
     * 流式对话
     * @param dto 请求参数
     * @return
     */
    @GetMapping(value = "/chat/sse")
    @CrossOrigin
    public SseEmitter chatSse(HttpServletResponse response, @ModelAttribute ChatGptDTO dto) {
        response.addHeader("Content-Type", "text/event-stream");
        try {
            return chatGptSseService.chat(dto.getContent(), dto.getModel(), dto.getMaxTokens(), dto.getTemperature());
        } catch (HttpException e) {
            throw new ErrorException("请求 openai 遇到点网络问题 HttpException");
        } catch (IORuntimeException e) {
            throw new ErrorException("请求 openai 遇到点网络问题 IORuntimeException");
        }
    }
}
